/*
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "os_obj.h" // RTOS object definitions
#include "sys_task.h"
#include "sys_init.h"
#include "common.h"

#define TEST_MODE MB_RTU_SLAVE



mb_baud_tab_create;

uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
	uint16_t reg_r[64];
	uint16_t reg_w[64];
	uint16_t pv_r[64];
	uint16_t pv_w[64];
	uint16_t obj_size;
} mb_tst_type;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);
void qc_task(const void *argv);
void modbus_task(const void *argv);

/******************************************************************************
 * @brief   modbus task creat.
 * @param   argv
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
osThreadDef(thd_modbus, modbus_task, 10, 0, 1024 * 2);
void mb_task_creat(void)
{
    osThreadCreate(osThread(thd_modbus),NULL);
}
obj_init_order5(mb_task_creat);

/******************************************************************************
 * @brief   modbus task.
 * @param   argv
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
void modbus_task(const void *argv)
{
	mb_cmd_buff_type mcmd;
	
	mb_obj_init(&mb.obj08);
	
	// slave config
	mb.obj08.slave_id = 1;
	mb.obj08.os_event_send = mb_os_send;
	mb.obj08.os_event_base = 1 << 4;
	mb.obj08.rtu_len_cut = 1;

	mb_obj_init(&mb.obj01);

	// master config
	mb.obj01.slave_id = 1;
	mb.obj01.rtu_master_delay_set = 3;
	mb.obj01.rcv_end_handle_comp = rcv_end_handle_comp;
	mb.obj01.os_event_send = mb_os_send;
	mb.obj01.os_event_base = 2 << 4;
	mb.obj01.rtu_len_cut = 1;

	// cmd config
	mcmd.device_id = 0;
	mcmd.cmd = FUN_CODE_READ_COILS;
	mcmd.dat = mb_tst.pv_w;
	mcmd.dat_addr = 0;
	mcmd.amount = 48;
	mcmd.call_back = 0;
	mb.obj01.api->stc_cmd_req(0, &mcmd);

	mcmd.cmd = FUN_CODE_READ_DISCRETE;
	mb.obj01.api->stc_cmd_req(1, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj01.api->stc_cmd_req(2, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj01.api->stc_cmd_req(3, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
	mb.obj01.api->stc_cmd_req(4, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_COIL;
	mb_tst.pv_w[0] = 0;
	mb.obj01.api->stc_cmd_req(5, &mcmd);

	// task handle
	for (;;)
	{
		osEvent event;

		// wait modbus event
		tx_semaphore_get(os_obj.sid_mb, ms_ticks(100));
		
		(void)event;

		mb_poll(&mb.obj08);

		mb_poll(&mb.obj01);

		mb_tst.obj_size = sizeof(mb.obj01);
	}
}

void rcv_end_handle_comp(uint8_t ErrSt){};
